﻿using Android.Util;
using Android.App;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using AndroidX.AppCompat.App;
using Google.Android.Material.BottomNavigation;
using Android.Database;
using Android.Database.Sqlite;
using System;
using System.IO;
using System.Threading;
using FluentFTP;
using Android.Content;

namespace KnowledgeInput
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity, BottomNavigationView.IOnNavigationItemSelectedListener
    {
        string tag = "MainActivity";
        LinearLayout content_layout = null;
        TextView path_title = null;
        EditText path_text = null;
        EditText ip_address = null;
        Button path_save = null;
        TextView status = null;
        string db_path;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            BottomNavigationView navigation = FindViewById<BottomNavigationView>(Resource.Id.navigation);
            navigation.SetOnNavigationItemSelectedListener(this);

            content_layout = FindViewById<LinearLayout>(Resource.Id.content_layout);
            path_title = FindViewById<TextView>(Resource.Id.path_title);
            path_text = FindViewById<EditText>(Resource.Id.path_text);
            ip_address = FindViewById<EditText>(Resource.Id.ip_address);
            path_save = FindViewById<Button>(Resource.Id.save);
            status = FindViewById<TextView>(Resource.Id.status);
            path_save.SetTag(Resource.Integer.type, -1);
            path_save.Click += OnButtonsClick;

            string current_path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            db_path = current_path + "/textbook.db";
            path_text.Text = db_path;

            ip_address.Text = "192.168.1.103";

            path_title.Visibility = ViewStates.Gone;
            path_text.Visibility = ViewStates.Gone;
            ip_address.Visibility = ViewStates.Gone;
            path_save.Visibility = ViewStates.Gone;
            status.Visibility = ViewStates.Gone;

            this.ShowSelect();
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
        public bool OnNavigationItemSelected(IMenuItem item)
        {
            switch (item.ItemId)
            {
                case Resource.Id.navigation_select:
                    this.ShowSelect();
                    return true;
                case Resource.Id.navigation_sync:
                    this.ShowSync();
                    return true; 
            }
            return false;
        }
        private void ShowSelect()
        {
            Log.Info(tag, "ShowSelect");
            content_layout.RemoveAllViews();
            if (File.Exists(db_path))
            {
                Log.Info(tag, "db_path exist");
                string[] columns = new string[] { "id", "article_name" };
                SQLite sql = new SQLite(this, db_path);
                SQLiteDatabase db = sql.ReadableDatabase;
                ICursor cursor = db.Query("article", columns, null, null, null, null, "id ASC");
                while (cursor.MoveToNext())
                {
                    int id_column_index = cursor.GetColumnIndex("id");
                    int name_column_index = cursor.GetColumnIndex("article_name");
                    Button button = new Button(this);
                    button.SetText(cursor.GetString(name_column_index), TextView.BufferType.Normal);
                    button.SetTag(Resource.Integer.id, cursor.GetInt(id_column_index));
                    button.SetTag(Resource.Integer.type, 0);
                    button.SetAllCaps(false);
                    button.Click += this.OnButtonsClick;
                    content_layout.AddView(button);
                }
            }
        }
        private void ShowSync()
        {
            content_layout.RemoveAllViews();

            path_title.Visibility = ViewStates.Visible;
            ip_address.Visibility = ViewStates.Visible;
            path_text.Visibility = ViewStates.Visible;
            path_save.Visibility = ViewStates.Visible;
            status.Visibility = ViewStates.Visible;
            content_layout.AddView(path_title);
            content_layout.AddView(ip_address);
            content_layout.AddView(path_text);
            content_layout.AddView(path_save);
            content_layout.AddView(status);
        }
        private void OnButtonsClick(object sender, EventArgs e)
        {
            Log.Info(tag, "test");
            Button b = (Button)sender;
            int type = (int)b.GetTag(Resource.Integer.type);
            int id = (int)b.GetTag(Resource.Integer.id);
            switch (type)
            {
                case -1:
                    status.Text = "正在开始……";
                    new Thread(new ThreadStart(() => {
                        string current_path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                        db_path = current_path + "/textbook.db";
                        FtpClient ftp_client = new FtpClient(ip_address.Text, "lee", "");
                        status.Text = "正在连接……";
                        ftp_client.Connect();
                        status.Text = "正在下载……";
                        FtpStatus ftp_status = ftp_client.DownloadFile(db_path, "textbook.db");
                        if (ftp_status == FtpStatus.Success || ftp_status == FtpStatus.Skipped)
                        {
                            status.Text = "同步成功";
                        }
                        else
                        {
                            status.Text = "同步失败";
                        }
                        ftp_client.Dispose();
                    })).Start();
                    break;
                case 0:
                    Log.Info(tag, "143");
                    Intent intent = new Intent(this, typeof(Tree));
                    Log.Info(tag, "145");
                    intent.PutExtra("id", id);
                    intent.PutExtra("db_path", db_path);
                    Log.Info(tag, "148");
                    this.StartActivity(intent);
                    break;
            }
        }
    }
}

